package com.hc.likelistenmusic.fragment

import android.graphics.Color
import android.util.Log
import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import android.widget.ImageView
import android.widget.SeekBar
import android.widget.SeekBar.OnSeekBarChangeListener
import android.widget.TextView
import com.hc.likelistenmusic.R
import com.hc.likelistenmusic.activity.LocalMusicActivity
import com.hc.likelistenmusic.util.LrcUtil
import com.hc.likelistenmusic.util.ScreenUtil
import com.hc.likelistenmusic.view.LrcView
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File

class LocalLrcFragment : LazyFragment(false) {
    val TAG = "HUACHEN_LrcFragment"
    lateinit var mLv_fl: LrcView
    lateinit var mIv_fl_pre: ImageView
    lateinit var mIv_fl_next: ImageView
    lateinit var mIv_fl_playorpause: ImageView
    lateinit var mIv_fl_back: ImageView
    lateinit var mIv_fl_playmode: ImageView
    lateinit var mIv_fl_empty_lrc: ImageView
    lateinit var mTv_fl_empty_lrc: TextView
    lateinit var mTv_fl_musicCurrentDuration: TextView
    lateinit var mTv_fl_musicTotalDuration: TextView
    lateinit var mSb_fl: SeekBar
    lateinit var mLocalMusicActivity: LocalMusicActivity
    var mLoadLocalLrcJob: Job? = null
    var mCurrentLocalMusicPath: String? = null
    val mEmptyDuration = "00:00"
    override fun initView(rootView: View) {
        mLocalMusicActivity = activity as LocalMusicActivity
        mLv_fl = rootView.findViewById(R.id.lv_fl)
        mIv_fl_pre = rootView.findViewById(R.id.iv_fl_pre)
        mIv_fl_next = rootView.findViewById(R.id.iv_fl_next)
        mIv_fl_playorpause = rootView.findViewById(R.id.iv_fl_playorpause)
        mIv_fl_back = rootView.findViewById(R.id.iv_fl_back)
        mIv_fl_playmode = rootView.findViewById(R.id.iv_fl_playmode)
        mIv_fl_empty_lrc = rootView.findViewById(R.id.iv_fl_empty_lrc)
        mTv_fl_empty_lrc = rootView.findViewById(R.id.tv_fl_empty_lrc)
        mTv_fl_musicCurrentDuration = rootView.findViewById(R.id.tv_fl_musicCurrentDuration)
        mTv_fl_musicTotalDuration = rootView.findViewById(R.id.tv_fl_musicTotalDuration)
        mSb_fl = rootView.findViewById(R.id.sb_fl)
        mIv_fl_pre.setOnClickListener {
            onNextOrPreClick(false)
        }
        mIv_fl_next.setOnClickListener {
            onNextOrPreClick(true)
        }
        mIv_fl_playorpause.setOnClickListener {
            onStartOrPauseClick()
        }
        mLv_fl.setOnApplyIndicatorLineListener { time, lrc ->
            handSyncLrcProgress(time)
        }
        mIv_fl_back.setOnClickListener {
            mLocalMusicActivity.moveToMusicFragment()
        }
        mIv_fl_playmode.setOnClickListener {
            mLocalMusicActivity.onPlayModeChangedFromLf()
        }
        mSb_fl.setOnSeekBarChangeListener(object : OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
                if (mLocalMusicActivity.onSeletedMusic()) {
                    mTv_fl_musicCurrentDuration.text = LrcUtil.formatLrcTime(progress)
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar) {

            }

            override fun onStopTrackingTouch(seekBar: SeekBar) {
                if (mLocalMusicActivity.onSeletedMusic()) {
                    mLv_fl.updateCurrentLine(seekBar.progress)
                    mLocalMusicActivity.handSyncProgress(seekBar.progress)
                } else {
                    seekBar.progress = 0
                }
            }
        })
    }

    override fun getLayoutResId(): Int {
        return R.layout.fragment_lrc
    }

    override fun onResume() {
        super.onResume()
        ScreenUtil.hideSoftInput(
            mLocalMusicActivity,
            mLocalMusicActivity.getSearchEditText()
        )
    }

    override fun startLazyLoad() {
        mCurrentLocalMusicPath?.let {
            val prep = it.substring(0, it.lastIndexOf("/"))
            val middle = it.substring(it.lastIndexOf("/"), it.lastIndexOf(".mp3"))
            val lrcPath = "${prep}Lrc${middle}.lrc"
            mLoadLocalLrcJob = CoroutineScope(Dispatchers.IO).launch {
                Log.d(TAG, "根据歌曲名加载歌词:${lrcPath}")
                val lrcs = LrcUtil.analysisLrcFromFile(File(lrcPath))
                if (lrcs.isNullOrEmpty()) {
                    mLv_fl.pauseAutoScroll()
                    withContext(Dispatchers.Main) {
                        mIv_fl_empty_lrc.visibility = VISIBLE
                        mTv_fl_empty_lrc.visibility = VISIBLE
                        mLv_fl.visibility = GONE
                    }
                } else {
                    mLv_fl.resumeAutoScroll()
                    withContext(Dispatchers.Main) {
                        mIv_fl_empty_lrc.visibility = GONE
                        mTv_fl_empty_lrc.visibility = GONE
                        mLv_fl.visibility = VISIBLE
                    }
                }
                mLv_fl.setLrcs(lrcs)
            }
        } ?: {
            mIv_fl_empty_lrc.visibility = VISIBLE
            mTv_fl_empty_lrc.visibility = VISIBLE
            mLv_fl.visibility = GONE
        }
    }

    fun onStartOrPauseClick() {
        mLocalMusicActivity.changeMfStartOrPause()
    }

    fun onNextOrPreClick(next: Boolean) {
        mLocalMusicActivity.handChangeNextSong(next)
    }

    fun handSyncLrcProgress(currentProgress: Int) {
        mLv_fl.updateCurrentLine(currentProgress)
        mLocalMusicActivity.handSyncProgress(currentProgress)
    }

    fun onMediaPlayerPrepared() {
        mLv_fl.setLrcTextColorPlaying(Color.GREEN)
        mIv_fl_playorpause.setImageResource(R.drawable.img_pause)
    }

    fun autoSyncLrcProgress(currentProgress: Int, duration: Int, currentLocalMusicPath: String?) {
        if (currentProgress == 0) {
            mCurrentLocalMusicPath = currentLocalMusicPath
            mTv_fl_musicCurrentDuration.text = mEmptyDuration
            mTv_fl_musicTotalDuration.text = LrcUtil.formatLrcTime(duration)
            mSb_fl.max = duration
            mSb_fl.progress = currentProgress
            LazyLoadFail()
            startLazyLoad()
        } else {
            mTv_fl_musicCurrentDuration.text = LrcUtil.formatLrcTime(currentProgress)
            mSb_fl.progress = currentProgress
            mSb_fl.max = duration
            mLv_fl.updateCurrentLine(currentProgress)
        }
    }

    fun showStartOrPause(show: Boolean) {
        if (show) {
            mLv_fl.setLrcTextColorPlaying(Color.GREEN)
            mIv_fl_playorpause.setImageResource(R.drawable.img_pause)
        } else {
            mLv_fl.setLrcTextColorPlaying(Color.RED)
            mIv_fl_playorpause.setImageResource(R.drawable.img_play)
        }
    }

    fun setNoLrcs() {
        if(::mLv_fl.isInitialized){
            mLv_fl.setLrcs(LrcUtil.analysisLrcFromFile(File("")))
            mLv_fl.pauseAutoScroll()
        }
    }

    fun onPlayModeChanged(mode: Int) {
        when (mode) {
            1 -> {
                mIv_fl_playmode.setImageResource(R.drawable.img_mode_list_repeat)
            }

            2 -> {
                mIv_fl_playmode.setImageResource(R.drawable.img_mode_single_repeat)
            }

            else -> {
                mIv_fl_playmode.setImageResource(R.drawable.img_mode_random_repeat)
            }
        }
    }

    fun onError() {
        mIv_fl_empty_lrc.visibility = VISIBLE
        mTv_fl_empty_lrc.visibility = VISIBLE
        if(::mLv_fl.isInitialized){
            mLv_fl.visibility = GONE
        }
    }
}